package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.MessageConstant;
import com.itheima.dao.MemberDao;
import com.itheima.dao.OrderDao;
import com.itheima.dao.OrderSettingDao;
import com.itheima.dao.SetmealDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.QueryPageBeano;
import com.itheima.entity.Result;
import com.itheima.pojo.CheckGroup;
import com.itheima.pojo.Member;
import com.itheima.pojo.Order;
import com.itheima.pojo.OrderSetting;
import com.itheima.pojo.Setmeal;
import com.itheima.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.*;

/**
 * 体检预约服务
 */
@Service(interfaceClass = OrderService.class,weight = 100)
@Transactional
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderSettingDao orderSettingDao;
    @Autowired
    private MemberDao memberDao;
    @Autowired
    private OrderDao orderDao;
    @Autowired
    private SetmealDao setmealDao;

    //体检预约
    public Result order(Map map) throws Exception {

        //1.检查当前日期是否进行了预约设置
        String orderDate = (String) map.get("orderDate");
        Date date = DateUtils.parseString2Date(orderDate);
        OrderSetting orderSetting = orderSettingDao.findByOrderDate(date);
        if(orderSetting == null){
            return new Result(false, MessageConstant.SELECTED_DATE_CANNOT_ORDER);
        }

        //2.检查预约日期是否预约已满
        int number = orderSetting.getNumber();//可预约人数
        int reservations = orderSetting.getReservations();//已预约人数
        if(reservations >= number){
            //预约已满，不能预约
            return new Result(false,MessageConstant.ORDER_FULL);
        }

        //检查当前用户是否为会员，根据手机号判断
        String telephone = (String) map.get("telephone");
        Member member = memberDao.findByTelephone(telephone);

        //3.防止重复预约
        if(member != null){
            Integer memberId = member.getId();
            int setmealId = Integer.parseInt((String)map.get("setmealId"));
            Order order = new Order(memberId, date, null, null, setmealId);
            List<Order> list = orderDao.findByCondition(order);
            if(list != null && list.size() > 0){
                //已经完成了预约，不能重复预约
                return new Result(false,MessageConstant.HAS_ORDERED);
            }
        }
        //可以预约，设置预约人数加一
        orderSetting.setReservations(orderSetting.getReservations()+1);
        orderSettingDao.editReservationsByOrderDate(orderSetting);

        // 4.检查当前用户是否为会员，如果是会员则直接完成预约，如果不是会员则自动完成注册并进行预约
        if(member == null){
            //当前用户不是会员，需要添加到会员表
            member = new Member();
            member.setName((String) map.get("name"));
            member.setPhoneNumber(telephone);
            member.setIdCard((String) map.get("idCard"));
            member.setSex((String) map.get("sex"));
            member.setRegTime(new Date());
            memberDao.add(member);
        }

        //5.保存预约信息到预约表
        Order order = new Order(member.getId(), date, (String)map.get("orderType"), Order.ORDERSTATUS_NO,
                Integer.parseInt((String)map.get("setmealId")));
        orderDao.add(order);
        return new Result(true, MessageConstant.ORDER_SUCCESS, order.getId());

    }

    //根据id查询预约信息，包括体检人信息、套餐信息
    public Map findById(Integer id) throws Exception {
        Map map = orderDao.findById4Detail(id);
        if(map != null){
            //处理日期格式
            Date orderDate = (Date) map.get("orderDate");
            map.put("orderDate", DateUtils.parseDate2String(orderDate));
        }
        return map;
    }




    //预约服务
    public Result submit(Order order, Integer setmealId) {
        Date orderDate = order.getOrderDate();
        String d = null;
        try {
            d=DateUtils.parseDate2String(orderDate);
        } catch (Exception e) {
            e.printStackTrace();
        }
        OrderSetting orderSetting = orderSettingDao.findByOrderDate2(d);
        if(orderSetting==null){
            return new Result(false, MessageConstant.SELECTED_DATE_CANNOT_ORDER);
        }
        int reservations = orderSetting.getReservations();
        int number = orderSetting.getNumber();
        if (reservations>=number){
            return new Result(false,MessageConstant.ORDER_FULL);
        }

        String phoneNumber = order.getPhoneNumber();      //获得预约手机号
        Member member = memberDao.findByTelephone(phoneNumber);  //通过手机号查询数据库是否有数据
        //检查当前用户是否为会员，如果是会员则直接完成预约，如果不是会员则自动完成注册并进行预约
        if (member == null) { //不是会员
            member = new Member();
            member.setName(order.getMemberName());
            member.setPhoneNumber(phoneNumber);
            member.setRegTime(new Date());
            memberDao.add(member);
        } else {
            //是会员的话判断是否重复预约
            //预约日期,预约的套餐ID是否一模一样
            Integer Id = member.getId();
            //通过会员ID查询是否存在预约订单
            List<Order> orderList = orderDao.findAllsetmealByMemberId(Id);
            if (orderList!=null&&orderList.size()>0){
                //查看是否有重复的订单
                Order checksame = orderDao.checksame(Id, orderDate, setmealId);
                if (checksame!=null){
                    return new Result(false,"存在重复订单");
                }
            }
        }
        //保存预约信息到预约表
        order.setMemberId(member.getId());
        order.setOrderType(Order.ORDERTYPE_TELEPHONE);
        order.setOrderStatus(Order.getOrderstatusNo());
        order.setSetmealId(setmealId);
        orderDao.add(order);

        //预约成功,设置预约人数加一
        orderSetting.setReservations(orderSetting.getReservations() + 1);
        orderSettingDao.editReservationsByOrderDate(orderSetting);

        return new Result(true, MessageConstant.ORDER_SUCCESS, order.getId());
    }

    //预约分页查询
    public PageResult findOrdersPage(QueryPageBeano queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();
        String startDate = queryPageBean.getStartDate();
        String endDate = queryPageBean.getEndDate();
        String orderType = queryPageBean.getOrderType();
        String orderStatus = queryPageBean.getOrderStatus();
        PageHelper.startPage(currentPage, pageSize);
        Page<Order> page = orderDao.selectByCondition(startDate, endDate, orderType, orderStatus, queryString);
        long total = page.getTotal();
        List<Order> rows = page.getResult();
        return new PageResult(total, rows);
    }

    @Override
    public Map findAllById(Integer id) {
        return orderDao.findAllById(id);
    }

    @Override
    public int findSetmealIdByOrderId(int id) {
        Map map = orderDao.findAllById(id);
        Integer setmealId = (Integer) map.get("setmealId");
        return setmealId;
    }

    @Override
    public void edit(Order order, Integer setmealId) {
        memberDao.editNameById(order);
        order.setSetmealId(setmealId);
        orderDao.edit(order);
    }

    //删除预约信息
    public void delete(Integer id) {
        orderDao.deleteById(id);
    }

    //更改预约状态
    public void changeStatus(Order order) {
        orderDao.changeStatus(order);
    }

    //获取当日预约人数
    public Map findByDate(Date startTimeDate, Date endTimeDate) {
        Map<String, Object> map = new HashMap<>();
        //通过时间的范围获取每天的预约人数循环遍历每一天
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(startTimeDate);
        List<String> listDate = new ArrayList<>();
        while (calendar.getTime().before(endTimeDate)) {
            listDate.add(dateFormat.format(calendar.getTime()));
            calendar.add(Calendar.DAY_OF_MONTH, 1);
        }


        List<Integer> listOrder = new ArrayList<>();
        List<Integer> listVisits = new ArrayList<>();

        for (String date : listDate
        ) {
            //获取当日预约人数
            Integer orderCount = orderDao.findOrderCountByDate(date);
            Integer visitsCountByDate = orderDao.findVisitsCountByDate(date);
            listOrder.add(orderCount);
            listVisits.add(visitsCountByDate);
        }
        //封装预约人数
        map.put("orderCount", listOrder);
        map.put("days",listDate);
        //获取未就诊人数
        map.put("visitCount", listVisits);
        return map;
    }

    //性别饼图统计
    @Override
    public List<Map<String, Object>> findSexCount() {
        return orderDao.findSexCount();
    }

    //年龄饼图统计
    @Override
    public List<Map<String, Object>> findAgeCount() {
        return orderDao.findAgeCount();
    }

    @Override
    public List<Map<String, Object>> queryAppointmentRecord(String startDate, String endDate, String phoneNumber) {

        List list=new ArrayList();

        List<Order> orderDates = orderDao.findOrderDates(startDate, endDate, phoneNumber);
        Map<String, Object> map = new HashMap<>();
        for (Order orderDate : orderDates) {
            map.put("orderId", orderDate.getId());
            Member byId = memberDao.findById(orderDate.getMemberId());
            map.put("memberName", byId.getName());
            Setmeal byId1 = setmealDao.findById(orderDate.getSetmealId());
            map.put("setmealId", byId1.getName());
            map.put("img", byId1.getImg());
            list.add(map);
        }
        return list;
    }

    @Override
    public Map findOrderDetailsById(Integer id) {
        return orderDao.findById4Details(id);
    }
}
